package cn.sccdlg.spring5.outxml.dao.impl;

import cn.sccdlg.spring5.outxml.dao.AccountDao;
import cn.sccdlg.spring5.outxml.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/10/19 21:11
 * 账户的持久层实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
    private static final Log log = LogFactory.getLog(AccountDaoImpl.class);
    /**
     * 查询运行对象
     */
    @Autowired
    private QueryRunner runner;

    @Override
    public List<Account> findAllAccount() {
        try {
            List<Account> list = runner.query("select * from account",
                    new BeanListHandler<Account>(Account.class));
            log.info("账户列表= " + list);
            return list;
        } catch (Exception e) {
            log.error("查询所有账户信息出错，异常信息= " + e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            Account account = runner.query("select * from account where id = ? ",
                    new BeanHandler<Account>(Account.class), accountId);
            log.info("账户信息= " + account);
            return account;
        } catch (Exception e) {
            log.error("查询账户失败，异常信息= " + e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            int save = runner.update("insert into account(name, money)values(?, ?)",
                    account.getName(), account.getMoney());
            log.info("保存记录数= " + save);
        } catch (Exception e) {
            log.error("保存账户失败，异常信息= " + e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try {
            int update = runner.update("update account set name = ?, money = ? where id = ?",
                    account.getName(), account.getMoney(), account.getId());
            log.info("更新记录数= " + update);
        } catch (Exception e) {
            log.error("更新账户失败，异常信息= " + e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try {
            int delete = runner.update("delete from account where id = ?", accountId);
            log.info("删除记录数= " + delete);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
